package a66weding.com.jiehuntong.view.holiday;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.TextView;


import org.xutils.common.util.DensityUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.common.WorkOrRelax;
import a66weding.com.jiehuntong.common.utils.CalendarUtil;
import a66weding.com.jiehuntong.common.utils.ChineseUpperCaser;
import a66weding.com.jiehuntong.common.utils.DateUtils;
import a66weding.com.jiehuntong.common.utils.LunarCalendar;

/**
 * Created by Administrator on 2016/6/26.
 */
public class MonthDateView extends View {
    private Context mContext;
    private final int NUM_COLUMNS = 7;
    private  int NUM_ROWS = 6;
    private Paint mPaint;
    private int mSelectDayColor = Color.parseColor("#FFFFFF");
    private int mSelectBGColor;
    private int mCurrentColor;
    private int mCircleColor;
    private int mCircleRedColor;
    private int mCircleWhiteColor;
    private int mEnableDateColor;
    private int mUnableDateColor;
    private int mRelaxColor;
    private int mWorkColor;
    private int mPriceColor;
    private int mLunarTextColor;
    private int mDateTextColor;
    private int mDateHeight;
    private int mCurrYear,mCurrMonth,mCurrDay;
    private int mCurrLunarYear,mCurrLunarMonth,mCurrLunarDay;
    private String mStrCurrLunDay;
    private int mSelYear,mSelMonth,mSelDay;
    private int mSelLunarYear,mSelLunarMonth,mSelLunarDay;

    private float mColumnSize,mRowSize;//列宽，行高
    private int mDaySize,mPriceSize;
//    private TextView tv_date,tv_week;
    private int weekRow;
    private int [][] daysString;
    private int mCircleRadius = 6;
    private DateClickListener dateClick;
    private int mMarginSize =1;
    private int minYear,minMonth,minDay,maxYear,maxMonth;
    //记录是否为国家法定假日
    private List<WorkOrRelax> daysWorkOrRelaxList = new ArrayList<WorkOrRelax>();
    private int mTouchSlop;
    private float startX;
    private float startY;
    private float startLunarX;
    private float startLunarY;
    private float mTextDistanceY;
    private float mHolidayTextsize;

    private float circleCenterX,circleCenterY;
    private Paint.FontMetrics fontMetrics;
    private int mCurrentweek;
    private int mSelectweek;
    private Canvas mCanvas;

    private boolean isSelected;


    private  List<String> holidayList;
    private PageChangeListener pageChangeListener;


    public MonthDateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext=context;
        initConstruct(context,attrs);
    }


    private void initConstruct(Context context,AttributeSet attrs){
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CalendarView);
        mEnableDateColor = typedArray.getColor(R.styleable.CalendarView_EnableDateColor, Color.parseColor("#000000"));
        mUnableDateColor = typedArray.getColor(R.styleable.CalendarView_UnableDateColor, Color.parseColor("#CBCBCB"));
        mCircleColor = typedArray.getColor(R.styleable.CalendarView_CircleColor, Color.parseColor("#f36e5d"));
        mCircleRedColor = typedArray.getColor(R.styleable.CalendarView_mCircleRedColor, Color.parseColor("#ec4545"));
        mCircleWhiteColor = typedArray.getColor(R.styleable.CalendarView_mCircleWhiteColor, Color.parseColor("#ffffff"));
        mRelaxColor = typedArray.getColor(R.styleable.CalendarView_RelaxColor, Color.parseColor("#65CD00"));
        mWorkColor = typedArray.getColor(R.styleable.CalendarView_WorkColor, Color.parseColor("#FF9B12"));
        mPriceColor = typedArray.getColor(R.styleable.CalendarView_PriceColor, Color.parseColor("#FF9B12"));
        mSelectBGColor = typedArray.getColor(R.styleable.CalendarView_SelectBGColor, Color.parseColor("#13A4D3"));
        mCurrentColor = typedArray.getColor(R.styleable.CalendarView_CurrentColor, Color.parseColor("#FF0000"));
        mLunarTextColor = typedArray.getColor(R.styleable.CalendarView_LunarText, Color.parseColor("#9e686464"));
        mDateTextColor = typedArray.getColor(R.styleable.CalendarView_DateText, Color.parseColor("#da262424"));
        mDateHeight = (int) typedArray.getDimension(R.styleable.CalendarView_DateHeight, DensityUtil.dip2px(50) );

        mDaySize = (int) typedArray.getDimension(R.styleable.CalendarView_DateSize, DensityUtil.dip2px(15));
        mPriceSize = (int) typedArray.getDimension(R.styleable.CalendarView_PriceSize, DensityUtil.dip2px(12));
        typedArray.recycle();
        Calendar calendar = Calendar.getInstance();
        mCircleRadius=DensityUtil.dip2px(8);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCurrYear = calendar.get(Calendar.YEAR);
        mCurrMonth = calendar.get(Calendar.MONTH);
        mCurrDay = calendar.get(Calendar.DATE);
        mCurrentweek = calendar.get(Calendar.DAY_OF_WEEK);

        int[] ints = LunarCalendar.solarToLunar(mCurrYear, mCurrMonth+1, mCurrDay);
        mCurrLunarYear=ints[0];
        mCurrLunarMonth=ints[1];
        mCurrLunarDay=ints[2];

        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mRowSize = mDateHeight;

        setSelectYearMonthDate(mCurrYear,mCurrMonth);

    }

    /**
     * 设置年月
     * @param year
     * @param month
     */
    public void setSelectYearMonth(int year,int month,int day){
        mSelYear = year;
        mSelMonth = month;
        mSelDay = day;
        int[] ints = LunarCalendar.solarToLunar(mSelYear, mSelMonth+1, mSelDay);
        mSelLunarYear=ints[0];
        mSelLunarMonth=ints[1];
        mSelLunarDay=ints[2];

    }

    /**
     * 设置选中的月份
     * @param year
     * @param month
     */
    private void setSelectYearMonthDate(int year,int month){
        mSelYear = year;
        mSelMonth = month;
        int[] ints = LunarCalendar.solarToLunar(year, month+1, 1);
        mSelLunarYear=ints[0];
        mSelLunarMonth=ints[1];


    }

    /**
     * 设置到指定日期
     * @param year
     * @param month
     * @param day
     */
    public void setSelectDate(int year,int month,int day){
        mSelYear = year;
        mSelMonth = month;
        mSelDay = day;
        int[] ints = LunarCalendar.solarToLunar(mSelYear, mSelMonth+1, mSelDay);
        mSelLunarYear=ints[0];
        mSelLunarMonth=ints[1];
        mSelLunarDay=ints[2];
        forceLayout();
        measure(0, 0);
        requestLayout();
        invalidate();
    }

    private void setSelectWeek(int colum){
        mSelectweek=colum;
    }
    public String getSelectWeek(){
        String week="";
        if(mSelectweek==0) {
            week="星期日";
        }else{
            week="星期"+ ChineseUpperCaser.paseIntegerToStr(mSelectweek);
        }
        return week;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if(widthMode == MeasureSpec.AT_MOST){
            widthSize = (int) (300 * getResources().getDisplayMetrics().density);
        }
        NUM_ROWS = getMonthRowNumber();
        heightSize = NUM_ROWS * mDateHeight;
        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        mCanvas=canvas;
        initSize();
        daysString = new int[6][7];
        String dayString;
        String lunarDayStr;
        String holiday;
        int mMonthDays = DateUtils.getMonthDays(mSelYear, mSelMonth);
        int weekNumber = DateUtils.getFirstDayWeek(mSelYear, mSelMonth);
        int column,row = 0;
        Paint.FontMetrics fontMetrics;
        for(int day = 0;day < mMonthDays;day++){
            dayString = (day + 1) + "";
            int[] ints = LunarCalendar.solarToLunar(mSelYear, mSelMonth+1, day + 1);
            lunarDayStr= CalendarUtil.getChinaDayString(ints[2]);
            column = (day+weekNumber - 1) % 7;
            row = (day+weekNumber - 1) / 7;
            daysString[row][column]=day + 1;
            //判断是否为节假日
             holiday = getHoliday(day + 1).trim();

            if(TextUtils.isEmpty(holiday)){
                holiday = lunarDayStr;
            }

            mPaint.setTextSize(mDaySize);
            mPaint.setTextAlign(Paint.Align.CENTER);

            startX = mColumnSize * column + circleCenterX;
            fontMetrics = mPaint.getFontMetrics();
            startY = mRowSize * row + circleCenterY -mTextDistanceY/2- ( fontMetrics.bottom);


            if(dayString.equals(mSelDay+"")){


                mPaint.setColor(mCircleColor);
                mPaint.setStyle(Paint.Style.FILL);
                float circleX = (float) (mColumnSize * column +	mColumnSize/2);
                float circley = (float) (mRowSize * row + mRowSize/2);
                canvas.drawCircle(circleX, circley, circleCenterY, mPaint);

                //记录第几行，即第几周
                weekRow = column;
            }


            //绘制休、上班
            drawWorkOrRelax(row,column,day + 1,canvas);
            mPaint.setStyle(Paint.Style.STROKE);
           if(dayString.equals(mCurrDay+"") && mCurrDay != mSelDay && mCurrMonth == mSelMonth){
                //正常月，选中其他日期，则今日为红色
                mPaint.setColor(mCurrentColor);
            }
            mPaint.setColor(mDateTextColor);
            if(dayString.equals(mSelDay+"")) {
                mPaint.setColor(mCircleWhiteColor);
            }else if((day + 1)<mCurrDay && mSelMonth<=mCurrMonth && mSelYear<=mCurrYear){
                mPaint.setColor(mLunarTextColor);
            }
            //画日期
            canvas.drawText(dayString, startX, startY, mPaint);
            //画农历
             drawLunarStr(holiday, row, column,dayString, canvas);
//            drawBgCircle(row,column,canvas);
            mPaint.setStyle(Paint.Style.STROKE);

            boolean isHoliday = isHoliday(dayString);
            if(isHoliday) {
                //画吉日
                drawHoliday(row,column,dayString,canvas);
            }

        }

    }

    /**
     * 初始化列宽行高
     */
    private void initSize(){
        mColumnSize = getWidth() / NUM_COLUMNS;
        mRowSize = getHeight() / NUM_ROWS;

        circleCenterX=mColumnSize/2;
        circleCenterY=mRowSize/2;
        mTextDistanceY=DensityUtil.dip2px(3);
        mHolidayTextsize=DensityUtil.dip2px(10);

    }

    /**
     * 绘制事务圆形
     * @param row
     * @param column
     * @param canvas
     */
    private void drawCircle(int row,int column,Canvas canvas){

            mPaint.setColor(mCircleColor);
            mPaint.setStyle(Paint.Style.FILL);
            float circleX = (float) (mColumnSize * column +	mColumnSize/2);
            float circley = (float) (mRowSize * row + mRowSize/2);
            canvas.drawCircle(circleX, circley, circleCenterY, mPaint);

    }

    private void drawBgCircle(int row,int column,Canvas canvas){
            mPaint.setColor(mCircleRedColor);
            mPaint.setStyle(Paint.Style.STROKE);
            float circleX = (float) (mColumnSize * column +	mColumnSize/2);
            float circley = (float) (mRowSize * row + mRowSize/2);
            canvas.drawCircle(circleX, circley, circleCenterY, mPaint);

    }

    /**
     * 绘制休息天
     * @param row
     * @param column
     * @param day
     * @param canvas
     */
    private void drawWorkOrRelax(int row,int column,int day,Canvas canvas){
        if(daysWorkOrRelaxList != null && daysWorkOrRelaxList.size() > 0){
            WorkOrRelax workOrRelax;
            for(int i=0;i<daysWorkOrRelaxList.size();i++){
                workOrRelax = daysWorkOrRelaxList.get(i);
                if(workOrRelax.day == day && workOrRelax.year == mSelYear && workOrRelax.month == mSelMonth + 1){
                    float pointX0 = mColumnSize * column + mMarginSize;
                    float pointY0 = mRowSize * row - mMarginSize;
                    float pointX1 = (float) (mColumnSize * column +	mColumnSize*0.5);
                    float pointY1 =  mRowSize * row + mMarginSize;
                    float pointX2 = mColumnSize * column + mMarginSize;
                    float pointY2 = (float) (mRowSize * row + mColumnSize*0.5);
                    Path path = new Path();
                    path.moveTo(pointX0, pointY0);
                    path.lineTo(pointX1, pointY1);
                    path.lineTo(pointX2, pointY2);
                    path.close();
                    mPaint.setStyle(Paint.Style.FILL);
                    if(workOrRelax.state == 0){//班
                        mPaint.setColor(mWorkColor);
                        canvas.drawPath(path, mPaint);
                        mPaint.setTextSize(mPriceSize);
                        mPaint.setColor(mSelectDayColor);
                        mPaint.measureText("班");
                        canvas.drawText("班", pointX0 + 4, pointY0 + mPaint.measureText("班"), mPaint);
                    }else{//休息
                        mPaint.setColor(mRelaxColor);
                        canvas.drawPath(path, mPaint);

                        mPaint.setTextSize(mPriceSize);
                        mPaint.setColor(mSelectDayColor);
                        canvas.drawText("休", pointX0 + 4, pointY0 + mPaint.measureText("休"), mPaint);
                    }
                }
            }
        }
    }
    private int baseline;
    private int mHeight;


    /**
     * 画吉日
     * @param canvas
     */
    private void drawHoliday(int row,int column,String dayString,Canvas canvas){

            mPaint.setColor(mCircleRedColor);
            mPaint.setStyle(Paint.Style.STROKE);
            float circleX = (float) (mColumnSize * column +	mColumnSize*0.15);
            float circley = (float) (mRowSize * row + mRowSize*0.2);
            canvas.drawCircle(circleX, circley, mCircleRadius, mPaint);
        mPaint.setColor(mCircleWhiteColor);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(circleX, circley, mCircleRadius, mPaint);


        mPaint.setColor(mCircleRedColor);

        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setTextSize(mHolidayTextsize);
        mPaint.setStyle(Paint.Style.STROKE);
        fontMetrics = mPaint.getFontMetrics();

        circley = circley + (fontMetrics.descent- fontMetrics.ascent)/2 - fontMetrics.bottom;

        canvas.drawText("吉", circleX, circley, mPaint);

    }


    private void drawLunarStr(String content,int row,int column,String dayString,Canvas canvas){
        mPaint.setTextSize(mPriceSize);
        mPaint.setColor(mLunarTextColor);
        if(dayString.equals(mSelDay+"")){
            mPaint.setColor(mCircleWhiteColor);
        }else if(column==0 || column==6){
            mPaint.setColor(mCircleRedColor);
        }
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        startLunarY =startY+mDaySize +mTextDistanceY;
        canvas.drawText(content, startX, startLunarY, mPaint);
    }

    /**
     * 绘制线条
     * @param canvas
     */
    private void drawLines(Canvas canvas){
        int rightX = getWidth();
        int BottomY = getHeight();
        int rowCount = getMonthRowNumber();
        int columnCount = 7;
        Path path;
        float startX = 0;
        float endX = rightX;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(mUnableDateColor);
        for(int row = 1; row <= rowCount ;row++){
            float startY = row * mRowSize;
            path = new Path();
            path.moveTo(startX, startY);
            path.lineTo(endX, startY);
            canvas.drawPath(path, mPaint);
        }

        float startY = 0;
        float endY = BottomY;
        for(int column =1; column < columnCount;column++){
            startX = column * mColumnSize;
            path = new Path();
            path.moveTo(startX, startY);
            path.lineTo(startX, endY);
            canvas.drawPath(path, mPaint);
        }



    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }


    /**
     * 获取总共行数
     * @return
     */
    private int getMonthRowNumber(){
        int mMonthDays = DateUtils.getMonthDays(mSelYear, mSelMonth);
        int weekNumber = DateUtils.getFirstDayWeek(mSelYear, mSelMonth);
        return (mMonthDays + weekNumber - 1) % 7 == 0 ? (mMonthDays + weekNumber - 1) / 7 : (mMonthDays + weekNumber - 1) / 7 + 1;
    }

    /**
     *获取节气节日
     * @param day
     * @return
     */
    private String getHoliday(int day){
        Calendar calendar = Calendar.getInstance();
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date myDate1 = dateFormat1.parse(mSelYear + "-" + (mSelMonth+1) + "-" +day);
            calendar.setTime(myDate1);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return new CalendarUtil(calendar).getHolidayMsg();
    }





    /**
     * 设置显示当前日期的控件
     * @param tv_date
     * 		显示日期
     * @param tv_week
     * 		显示周
     */
    public void setTextView(TextView tv_date,TextView tv_week){
        invalidate();
    }

    private int downX = 0,downY = 0;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventCode=  event.getAction();
        switch(eventCode){
            case MotionEvent.ACTION_DOWN:
                downX = (int) event.getX();
                downY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                int upX = (int) event.getX();
                int upY = (int) event.getY();
                if(upX-downX > 0 && Math.abs(upX-downX) > mTouchSlop && Math.abs(upX-downX)>100){//左滑
                    onLeftClick();

                }else if(upX-downX < 0 && Math.abs(upX-downX) > mTouchSlop &&  Math.abs(upX-downX)>100){//右滑
                    onRightClick();
                }
                if(Math.abs(upX-downX) < 10 && Math.abs(upY - downY) < 10){//点击事件
//                    performClick();
                    doClickAction((upX + downX)/2,(upY + downY)/2);
                }
                break;
        }
        return true;
    }

    /**
     * 执行点击事件
     * @param x
     * @param y
     */
    private void doClickAction(int x,int y){
        int row = (int) (y / mRowSize);
        int column = (int) (x / mColumnSize);
        setSelectYearMonth(mSelYear,mSelMonth,daysString[row][column]);
        setSelectWeek(column);
        invalidate();
        if(dateClick != null){
            dateClick.onDateClick();
        }
    }

    /**
     * 左点击，日历向后翻页
     */
    public void onLeftClick(){
        if(minYear == mSelYear && minMonth == mSelMonth + 1)return;
        int year = mSelYear;
        int month = mSelMonth;
        int day = mSelDay;
        if(month == 0){//若果是1月份，则变成12月份
            year = mSelYear-1;
            month = 11;
        }else if(DateUtils.getMonthDays(year, month) == day){
            month = month-1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month-1;
        }
        if(pageChangeListener!=null) {
            pageChangeListener.onPageChange(year,month+1);
        }
        setSelectYearMonth(year,month,day);
        forceLayout();
        measure(0, 0);
        requestLayout();
        invalidate();
    }

    /**
     * 右点击，日历向前翻页
     */
    public void onRightClick(){
        if(maxYear == mSelYear && maxMonth == mSelMonth + 1)return;
        int year = mSelYear;
        int month = mSelMonth;
        int day = mSelDay;
        if(month == 11){//若果是12月份，则变成1月份
            year = mSelYear+1;
            month = 0;
        }else if(DateUtils.getMonthDays(year, month) == day){
            month = month + 1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month + 1;
        }
        if(pageChangeListener!=null) {
            pageChangeListener.onPageChange(year,month+1);
        }
        setSelectYearMonth(year,month,day);
        forceLayout();
        measure(0, 0);
        requestLayout();
        invalidate();
    }



    /**
     * 获取选择的年份
     * @return
     */
    public int getmSelYear() {
        return mSelYear;
    }
    /**
     * 获取选择的月份
     * @return
     */
    public int getmSelMonth() {
        return mSelMonth;
    }
    /**
     * 获取选择的日期
     *
     */
    public int getmSelDay() {
        return this.mSelDay;
    }

    /**
     * 选择日期的颜色，默认为白色
     * @param mSelectDayColor
     */
    public void setmSelectDayColor(int mSelectDayColor) {
        this.mSelectDayColor = mSelectDayColor;
    }

    /**
     * 选中日期的背景颜色，默认蓝色
     * @param mSelectBGColor
     */
    public void setmSelectBGColor(int mSelectBGColor) {
        this.mSelectBGColor = mSelectBGColor;
    }
    /**
     * 当前日期不是选中的颜色，默认红色
     * @param mCurrentColor
     */
    public void setmCurrentColor(int mCurrentColor) {
        this.mCurrentColor = mCurrentColor;
    }


    /**
     * 日期的大小，默认18sp
     * @param mDaySize
     */
    public void setmDaySize(int mDaySize) {
        this.mDaySize = mDaySize;
    }

    /**
     * 设置休班天数
     * @param daysWorkOrRelaxList
     */
    public void setDaysWorkOrRelaxList(List<WorkOrRelax> daysWorkOrRelaxList) {
        this.daysWorkOrRelaxList = daysWorkOrRelaxList;
    }





    /***
     * 设置圆圈的半径，默认为6
     * @param mCircleRadius
     */
    public void setmCircleRadius(int mCircleRadius) {
        this.mCircleRadius = mCircleRadius;
    }

    /**
     * 设置圆圈的半径
     * @param mCircleColor
     */
    public void setmCircleColor(int mCircleColor) {
        this.mCircleColor = mCircleColor;
    }




    /**
     * 跳转至今天
     */
    public void setTodayToView(){
        setSelectYearMonth(mCurrYear,mCurrMonth,mCurrDay);
        invalidate();
    }

    /**
     * 设置日期的点击回调事件
     * @author shiwei.deng
     *
     */
    public interface DateClickListener{
        public void onDateClick();
    }

    /**
     * 设置页面切换回调事件
     * @author shiwei.deng
     *
     */
    public interface PageChangeListener{
        public void onPageChange(int year, int month);
    }

    /**
     * 设置日期点击事件
     * @param dateClick
     */
    public void setDateClick(DateClickListener dateClick) {
        this.dateClick = dateClick;
    }

    public void setPageChangeListener(PageChangeListener pageChangeListener) {
        this.pageChangeListener = pageChangeListener;
    }

    public List<String> getHolidayList() {
        return holidayList;
    }

    public void setHolidayList(List<String> holidayList) {
        this.holidayList = holidayList;
    }

    public boolean isHoliday(String days){
        if(holidayList.contains(days)) {
           return true;
        }
        return false;
    }

}
